package com.fzq.web;


import cn.hutool.core.util.StrUtil;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;

public class Test {

    private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";
    private static final String KEY = "zx--sc--dzda--zq";

    public static String aesDecrypt(String encryptStr) throws Exception {
        return StrUtil.isEmpty(encryptStr) ? null : aesDecryptByBytes(base64Decode(encryptStr));
    }


    /**
     * AES解密
     * @param encryptBytes 待解密的byte[]
     * @return 解密后的String
     * @throws Exception
     */
    public static String aesDecryptByBytes(byte[] encryptBytes) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);

        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(KEY.getBytes(), "AES"));
        byte[] decryptBytes = cipher.doFinal(encryptBytes);
        return new String(decryptBytes);
    }
//
//    @SuppressWarnings("restriction")
    public static byte[] base64Decode(String base64Code) throws Exception{
        return StrUtil.isEmpty(base64Code) ? null : java.util.Base64.getDecoder().decode(base64Code);
    }
//
//    public static String base64Encode(byte[] bytes){
//        return Base64.encodeBase64String(bytes);
//    }
//
//
//    public static byte[] aesEncryptToBytes(String content) throws Exception {
//        KeyGenerator kgen = KeyGenerator.getInstance("AES");
//        kgen.init(128);
//        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
//        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(KEY.getBytes(), "AES"));
//
//        return cipher.doFinal(content.getBytes("utf-8"));
//    }
//
//    public static String aesEncrypt(String content) throws Exception {
//        return base64Encode(aesEncryptToBytes(content));
//    }

    public static void main(String[] args) throws Exception {
        System.out.println(aesDecrypt("Pyhk+hfgbdXggW3+yaZBPA=="));
//        System.out.println(aesEncrypt("123456w"));
    }
}
